/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hhf.transaction;

import hhf.logger.LoggerName;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.transaction.Status;
import javax.transaction.TransactionSynchronizationRegistry;
import org.slf4j.Logger;

/**
 *
 * @author François
 */
@TransactionLogged
@Interceptor
public class TransactionLogger {
	@Inject
	@LoggerName("TRANSACTION")
	Logger logger;
	@Resource(lookup="java:comp/TransactionSynchronizationRegistry")
	private TransactionSynchronizationRegistry transactionRegistry;
	
	@AroundInvoke
	public Object logTransaction(InvocationContext ctx) throws Exception {
		String name = ctx.getTarget().getClass().getName();
		String m = ctx.getMethod().getName();
		logger.info("\nBEFORE : "+name+"."+m+" : "+getStatus()+"\n"+transactionRegistry.getTransactionKey());
		Object o = ctx.proceed();
		logger.info("\nAFTER  : "+name+"."+m+" : "+getStatus()+"\n"+transactionRegistry.getTransactionKey());
		return o;
	}

	private String getStatus() {
		int status = transactionRegistry.getTransactionStatus();
		switch(status) {
			case Status.STATUS_ACTIVE:
				return "STATUS_ACTIVE";
			case Status.STATUS_COMMITTED:
				return "STATUS_COMMITTED";
			case Status.STATUS_COMMITTING:
				return "STATUS_COMMITTING";
			case Status.STATUS_MARKED_ROLLBACK:
				return "STATUS_MARKED_ROLLBACK";
			case Status.STATUS_NO_TRANSACTION:
				return "STATUS_NO_TRANSACTION";
			case Status.STATUS_PREPARED:
				return "STATUS_PREPARED";
			case Status.STATUS_PREPARING:
				return "STATUS_PREPARING";
			case Status.STATUS_ROLLEDBACK:
				return "STATUS_ROLLEDBACK";
			case Status.STATUS_ROLLING_BACK:
				return "STATUS_ROLLING_BACK";
			case Status.STATUS_UNKNOWN:
				return "STATUS_UNKNOWN";
			default :
				return "OTHER";
		}
	}

}
